package view;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

import videoGrabber.CamAccess;
import videoGrabber.VideoGrabber;

/**
 * Shows the main window with the video stream and the menu
 * @author Daniel Mohr, Daniela Grammlich
 */
public class Gui extends JFrame implements ActionListener{

	private static final long serialVersionUID = 1L;
	private JMenuBar videoMenu;
	private JMenu video;
	private JMenu file;
	private JMenu frameMenu;
	private JMenuItem exit;
	private JMenuItem start;
	private JMenuItem stop;
	private JMenuItem grabFrame;
	private JMenuItem saveFrame;
	VideoGrabber grabber;
	CamAccess access;

	public Gui(VideoGrabber grabber,  CamAccess access){
		this.grabber = grabber;
		this.access = access;
		initialiseGui();
	}

	/**
	 * Initializes the gui and all its components
	 */
	public void initialiseGui(){
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent ev){	
				grabber.closeXML();
				System.exit(0);
		}
		});
		setLayout(new BorderLayout());
		setSize(800,600);

		videoMenu = new JMenuBar();
		
		file = new JMenu("File");
		video = new JMenu("Video");
		frameMenu = new JMenu("Frame");

		start = new JMenuItem("Start");
		start.addActionListener(this);
		stop = new JMenuItem("Stop");
		stop.addActionListener(this);

		exit = new JMenuItem("Beenden");
		exit.addActionListener(this);
		
		grabFrame = new JMenuItem("Grab Frame");
		grabFrame.addActionListener(this);
		saveFrame = new JMenuItem("Save Frame");
		saveFrame.addActionListener(this);
		
		video.add(start);
		video.add(stop);
		file.add(exit);
		frameMenu.add(grabFrame);
		frameMenu.add(saveFrame);
		videoMenu.add(file);
		videoMenu.add(video);
		videoMenu.add(frameMenu);
		setJMenuBar(videoMenu);
		
		JPanel panel = new JPanel();
		Component com;
		if((com = this.grabber.getPlayer().getVisualComponent()) != null){		
			panel.add(com);
			add(panel,BorderLayout.NORTH);
			this.grabber.startPlayer();
		}
		setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		if(event.getSource() == exit){
			grabber.closeXML();
			System.exit(0);
		}else if(event.getSource() == start){
				this.grabber.startPlayer();
		}else if(event.getSource() == stop){
				this.grabber.stopPlayer();
		}else if(event.getSource() == grabFrame){
			try {
				this.grabber.grabFrame();
			} catch (IOException e) { 
				e.printStackTrace();
			}
		}else if(event.getSource() == saveFrame){
			this.grabber.saveFrame();
		}
	}
}
